from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile, College


class UserCreateForm(UserCreationForm):
    """用户创建表单"""
    email = forms.EmailField(required=True, label='邮箱')
    first_name = forms.CharField(max_length=30, required=True, label='姓名')
    role = forms.ChoiceField(
        choices=UserProfile.ROLE_CHOICES,
        label='角色'
    )
    college = forms.ModelChoiceField(
        queryset=College.objects.all(),
        required=False,
        empty_label='请选择学院',
        label='所属学院',
        help_text='仅二级学院使用者需要选择'
    )
    
    class Meta:
        model = User
        fields = ('username', 'first_name', 'email', 'password1', 'password2')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 添加CSS类
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
    
    def clean(self):
        cleaned_data = super().clean()
        role = cleaned_data.get('role')
        college = cleaned_data.get('college')
        
        if role == 'college' and not college:
            raise forms.ValidationError('二级学院使用者必须选择所属学院')
        
        return cleaned_data
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.is_active = True  # 默认激活用户
        
        if commit:
            user.save()
            # 创建用户信息
            UserProfile.objects.create(
                user=user,
                role=self.cleaned_data['role'],
                college=self.cleaned_data.get('college')
            )
        return user


class UserProfileForm(forms.ModelForm):
    """用户信息编辑表单"""
    class Meta:
        model = UserProfile
        fields = ('role', 'college')
        widgets = {
            'role': forms.Select(attrs={'class': 'form-control'}),
            'college': forms.Select(attrs={'class': 'form-control'}),
        }
    
    def clean(self):
        cleaned_data = super().clean()
        role = cleaned_data.get('role')
        college = cleaned_data.get('college')
        
        if role == 'college' and not college:
            raise forms.ValidationError('二级学院使用者必须选择所属学院')
        
        return cleaned_data
